package cmd

import (
	"cmd/internal/timer"
	"github.com/spf13/cobra"
	"log"
	"strconv"
	"strings"
	"time"
)

var calculateTime string
var duration string

var timeCmd = &cobra.Command{
	Use:   "time",
	Short: "时间格式处理",
	Long:  "时间格式处理",
	Run: func(cmd *cobra.Command, args []string) {

	},
}

func init() {
	timeCmd.AddCommand(nowTimeCmd)
	timeCmd.AddCommand(calulateTimeCmd)

	calulateTimeCmd.Flags().StringVarP(&calculateTime, "calculate", "c", "", `需要计算的时间,有效单位为时间戳或已格式化的时间`)
	calulateTimeCmd.Flags().StringVarP(&duration, "duration", "d", "", `持续时间,有效单位为"ns", "us"(or μs), "ms", "s", "m", "h"`)
}

var nowTimeCmd = &cobra.Command{
	Use:   "now",
	Short: "获取当前时间",
	Long:  "获取当前时间",
	Run: func(cmd *cobra.Command, args []string) {
		time := timer.GetNowTime()
		log.Printf("当前时间为: %s, %d", time.Format("2006-01-02 15:04:05"), time.Unix())
	},
}

var calulateTimeCmd = &cobra.Command{
	Use:   "calc",
	Short: "计算所需时间",
	Long:  "计算所需时间",
	Run: func(cmd *cobra.Command, args []string) {
		var currentTime time.Time
		var layout = "2006-01-02 15:04:05"
		if calculateTime == "" {
			currentTime = timer.GetNowTime()
		} else {
			var err error
			space := strings.Count(calculateTime, " ")
			if space == 0 {
				layout = "2006-01-02"
			} else if space == 1 {
				layout = "2006-01-02 15:04:05"
			}
			currentTime, err = time.Parse(layout, calculateTime)
			if err != nil {
				atoi, _ := strconv.Atoi(calculateTime)
				currentTime = time.Unix(int64(atoi), 0)
			}
		}
		t, err := timer.GetCalculateTime(currentTime, duration)
		if err != nil {
			log.Fatalln("timer.GetCalculateTime err: %v", err)
		}
		log.Printf("当前时间为: %s, %d", t.Format("2006-01-02 15:04:05"), t.Unix())
	},
}
